import { createContext, useRef, ReactNode, useContext } from 'react';

interface FocusContextProps {
  registerInput: (name: string, ref: HTMLInputElement | HTMLTextAreaElement) => void;
  focusInput: (name: string) => void;
  removeFocusedInput(): void;
}

const InputFocusContext = createContext<FocusContextProps | undefined>(undefined);

interface InputFocusProviderProps {
  children: ReactNode;
}

export const InputFocusProvider: React.FC<InputFocusProviderProps> = ({ children }) => {
  const inputRefs = useRef<{ [key: string]: HTMLInputElement | HTMLTextAreaElement }>({});

  const registerInput = (name: string, ref: HTMLInputElement | HTMLTextAreaElement) => {
    if (inputRefs.current !== null) inputRefs.current[name] = ref;
  };

  const removeFocusedInput = () => {
    for (const key in inputRefs.current) {
      if (inputRefs.current[key] !== null) {
        if (Object.prototype.hasOwnProperty.call(inputRefs.current, key)) {
          inputRefs.current[key].classList.remove('visible');
        }
      }
    }
  }

  const focusInput = (name: string) => {
    if (inputRefs.current[name]) {
      removeFocusedInput()
      inputRefs.current[name].classList.add('visible');
      inputRefs.current[name].focus();
    }
  };

  return (
    <InputFocusContext.Provider value={{ registerInput, focusInput, removeFocusedInput }}>
      {children}
    </InputFocusContext.Provider>
  );
};

export const useInputFocusContext = (): FocusContextProps => {
  const context = useContext(InputFocusContext);
  if (!context) {
    throw new Error('useInPutFocusContext must be used within a InputFocusProvider');
  }
  return context;
};

export default useInputFocusContext;



